package com.linrui.user.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.linrui.basic.constants.WxConstants;
import com.linrui.basic.utils.AjaxResult;
import com.linrui.basic.utils.HttpClientUtils;
import com.linrui.user.domain.Logininfo;
import com.linrui.user.domain.Wxuser;
import com.linrui.user.mapper.LogininfoMapper;
import com.linrui.user.mapper.WxuserMapper;
import com.linrui.user.service.IWxuserService;
import com.linrui.basic.service.impl.BaseServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author linrui
 * @since 2022-11-17
 */
@Service
public class WxuserServiceImpl extends BaseServiceImpl<Wxuser> implements IWxuserService {

    @Autowired
    private WxuserMapper wxuserMapper;
    @Autowired
    private LogininfoMapper logininfoMapper;
    @Autowired
    private RedisTemplate redisTemplate;

    @Override
    public AjaxResult wechatLogin(String code) {
        //根据授权code获取微信用户的accessToken和用户的openid
        String accessurl = WxConstants.GET_ACK_URL
                .replace("APPID", WxConstants.APPID)
                .replace("SECRET", WxConstants.SECRET)
                .replace("CODE", code);
        String accessStr = HttpClientUtils.httpGet(accessurl);
        JSONObject accessObj = JSONObject.parseObject(accessStr);
        //发起获取accessToken和openid的请求
        String accessToken = accessObj.getString("access_token");
        String openid = accessObj.getString("openid");
        Wxuser wxuser = wxuserMapper.findByOpenid(openid);
        //据openid判断是否已经绑定用户
        if (Objects.nonNull(wxuser)){
            // 2.1 已经绑定用户，就做免密登录
            // 2.1.1 通过用户ID获取logininfo信息
            Logininfo logininfo = logininfoMapper.findByUserId(wxuser.getUserId());
            // 免密登录
            Map<String, Object> map = logininfoRedis(logininfo);
            return AjaxResult.me().setResult(map);
        }else {
            // 2.2 如果没有绑定过，就携带着accessToken和openid跳转到绑定页面，去绑定手机号
            Map<String, Object> map = new HashMap<>();
            map.put("accessToken",accessToken);
            map.put("openid", openid);
            return AjaxResult.me().setSuccess(false).setMessage("toBind").setResult(map);
        }
    }

    private Map<String ,Object> logininfoRedis(Logininfo logininfo) {
        // 4 redis操作
        // 4.1 生成一个随机字符串
        String token = UUID.randomUUID().toString();
        // 4.2 通过uuid作为redis的key，存入用户信息和权限信息
        redisTemplate.opsForValue().set("token", logininfo,30, TimeUnit.MINUTES);
        // 5 返回token和用户信息
        Map<String ,Object> map = new HashMap<>();
        map.put("token", token);
        map.put("logininfo", logininfo);
        return map;
    }
}
